<template>
	<view class="pages-upload">
		<view class="upload">
			<u-upload :action="action" :header="header" :multiple="false" @on-success="success" ref="upload"
				:max-count="maxSize" :file-list="fileList" :width='uploadWidth' :height='uploadHeight'
				@on-remove='remove' :source-type="['camera','album']" :capture="['camera','album']">
			</u-upload>
		</view>
	</view>
</template>

<script>
	import config from '@/config'
	import {
		getToken
	} from '@/utils/auth.js'
	export default {
		name: "q-upload",
		props: {
			maxSize: {
				type: Number,
				default: 5,
			},
			formData: {
				type: Object,
				default: () => {
					return {}
				}
			},
			keyName: {
				type: String,
				default: ''
			},
			uploadWidth: {
				type: String,
				default: '130rpx'
			},
			uploadHeight: {
				type: String,
				default: '130rpx'
			},
			externalList: {
				type: Array,
				default () {
					return []
				}
			}
		},
		data() {
			return {
				// 提交地址
				action: config.imgUrl + '/common/upload',
				header: {
					Authorization: ''
				},
				fileList: [],
				list: []
			};
		},
		created() {
			//获取token 不要删除空格
			this.header.Authorization = 'Bearer ' + getToken()

		},
		mounted() {},
		watch: {
			externalList: {
				handler() {
					this.fileList = []
					let arr = []
					let arr2 = []
					this.externalList.forEach(e => {
						arr.push({
							url: this.$img + e
						})
						arr2.push(e)
					})
					this.fileList = arr
					this.list = arr2
				},
				deep: true
			}
		},
		methods: {
			remove(a) {
				this.list.splice(a, 1)
				console.log('this.list', this.list);
				this.$emit('change', this.list.join(','))
				this.$set(this.formData, this.keyName, this.list.join(','))
			},
			init(url) {
				// 判断是否有图片
				if (url) {
					this.fileList = [];
					url.split(',').forEach(e => {
						this.fileList.push({
							url: this.$img + url
						})
						this.list.push(e)
					})
				}
			},
			success(res) {
				if (res.code !== 200) {
					//清空上传数组
					this.$refs.upload.clear()
					uni.showToast({
						icon: 'none',
						title: "上传失败,请重试"
					})
					return
				}
				this.list.push(res.fileName)
				console.log(this.list.join(','))
				this.$emit('change', this.list.join(','))
				this.$set(this.formData, this.keyName, this.list.join(','))
			},
		},
	}
</script>

<style scoped>
	.pages-upload {
		width: 100%;
		display: flex;

	}
</style>